import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    redirect: '/index',
    component: () => import('../layout/totalLayout.vue'),
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import('../views/index/index.vue'),
        meta:{
          pageTitle:"首页"
        }
      },
      {
        path:'/training',
        name:'training',
        component: () => import('../views/training/index.vue'),
        meta:{
          pageTitle:"培训管理"
        }
      },
      {
        path:'/userManage',
        name:'userManage',
        component: () => import('../views/userManage/index.vue'),
        meta:{
          pageTitle:"用户管理"
        }
      },
      {
        path:'/enlists',
        name:'enlists',
         component: () => import('../views/enlists/index.vue'),
        meta:{
          pageTitle:"报名记录"
        }
      },
      {
        path:'/video',
        name:'video',
        component: () => import('../views/video/index.vue'),
        meta:{
          pageTitle:"视频管理"
        }
      },
      {
        path:'/system',
        name:'system',
        component: () => import('../views/system/index.vue'),
        meta:{
          pageTitle:"系统设置"
        }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("Authorization");
  const loginData = JSON.parse(localStorage.getItem('loginData'))
  // 白名单路径（不需要登录的页面）
  const whiteList = ['/'];
  

  // 判断是否要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else if (whiteList.includes(to.path)) {
    if (token) {
      next('/main'); // 已登录用户访问登录页时跳转到主页
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;